<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
<style>
  /* 全局样式 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: #1a1a1a;
    font-family: Arial, sans-serif;
    color: #fff;
}

/* 游戏包装器 */
.game-wrapper {
    max-width: 1000px;
    width: 100%;
    padding: 20px;
}

/* 游戏头部 */
.game-header {
    text-align: center;
    margin-bottom: 20px;
}

.game-header h1 {
    color: #00f7ff;
    text-shadow: 0 0 10px rgba(0, 247, 255, 0.5);
    margin-bottom: 15px;
}

.game-info {
    display: flex;
    justify-content: space-between;
    background: rgba(0, 247, 255, 0.1);
    padding: 10px 20px;
    border-radius: 5px;
    border: 1px solid rgba(0, 247, 255, 0.3);
    margin-bottom: 10px;
}

/* 特殊效果容器 */
.effects-container {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 10px;
}

.effect-item {
    background: rgba(0, 0, 0, 0.5);
    padding: 5px 10px;
    border-radius: 5px;
    font-weight: bold;
    animation: pulse 1.5s infinite;
}

@keyframes pulse {
    0% { opacity: 0.7; }
    50% { opacity: 1; }
    100% { opacity: 0.7; }
}

/* 游戏容器 */
.game-container {
    background: radial-gradient(circle at 50% 20%, #0a0a2e, #000);
    border: 2px solid #00f7ff;
    box-shadow: 0 0 30px rgba(0, 247, 255, 0.3);
    padding: 20px;
    border-radius: 10px;
    margin-bottom: 20px;
    position: relative;
}

/* 障碍物样式 */
.obstacle {
    position: absolute;
    background: linear-gradient(135deg, #d4b483, #8b6b43);
    border: 1px solid #a89060;
    box-shadow: 0 0 10px rgba(212, 180, 131, 0.5);
    border-radius: 4px;
    animation: obstacleGlow 2s infinite alternate;
}

@keyframes obstacleGlow {
    from {
        box-shadow: 0 0 10px rgba(212, 180, 131, 0.5);
    }
    to {
        box-shadow: 0 0 15px rgba(212, 180, 131, 0.8);
    }
}

/* 画布样式 */
#gameCanvas {
    background: rgba(0, 0, 0, 0.8);
    border: 1px solid #00f7ff;
    display: block;
    margin: 0 auto;
}

/* 游戏控制 */
.game-controls {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
}

.control-group {
    display: flex;
    align-items: center;
    gap: 10px;
}

.button-group {
    display: flex;
    gap: 10px;
}

/* 速度控制滑块 */
#speedControl {
    width: 150px;
    accent-color: #00f7ff;
    background: rgba(0, 247, 255, 0.1);
    border-radius: 5px;
}

/* 难度选择下拉菜单 */
.difficulty-select {
    padding: 5px 10px;
    background: rgba(0, 247, 255, 0.1);
    border: 1px solid rgba(0, 247, 255, 0.3);
    border-radius: 5px;
    color: #fff;
    cursor: pointer;
    font-size: 14px;
    outline: none;
}

.difficulty-select option {
    background: #0a0a2e;
    color: #fff;
}

/* 按钮样式 */
button {
    padding: 8px 15px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-weight: bold;
}

.primary-btn {
    background: #00f7ff;
    color: #000;
}

.secondary-btn {
    background: rgba(0, 247, 255, 0.2);
    color: #00f7ff;
    border: 1px solid #00f7ff;
}

button:hover {
    transform: scale(1.05);
    box-shadow: 0 0 15px rgba(0, 247, 255, 0.5);
}

button:active {
    transform: scale(0.95);
}

/* 游戏说明 */
.game-footer {
    background: rgba(0, 247, 255, 0.1);
    border-radius: 10px;
    padding: 20px;
    border: 1px solid rgba(0, 247, 255, 0.3);
}

.game-instructions h2 {
    color: #00f7ff;
    margin-bottom: 15px;
    text-align: center;
}

.instructions-content {
    display: flex;
    justify-content: space-around;
    gap: 20px;
}

.control-instructions, .game-rules, .food-types {
    flex: 1;
}

.instructions-content h3 {
    color: #00f7ff;
    margin-bottom: 10px;
}

.instructions-content ul {
    list-style: none;
}

.instructions-content li {
    margin: 5px 0;
    padding-left: 20px;
    position: relative;
}

.instructions-content li::before {
    content: "•";
    color: #00f7ff;
    position: absolute;
    left: 0;
}

/* 食物图标 */
.food-icon {
    display: inline-block;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    margin-right: 5px;
    vertical-align: middle;
}

.food-icon.normal {
    background: #ff0066;
    box-shadow: 0 0 5px #ff0066;
}

.food-icon.speedBoost {
    background: #00ff88;
    box-shadow: 0 0 5px #00ff88;
}

.food-icon.doubleScore {
    background: #ffff00;
    box-shadow: 0 0 5px #ffff00;
}

.food-icon.shield {
    background: #00f7ff;
    box-shadow: 0 0 5px #00f7ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .game-wrapper {
        padding: 10px;
    }
    
    .game-info {
        flex-direction: column;
        gap: 10px;
    }
    
    .instructions-content {
        flex-direction: column;
    }
    
    .game-controls {
        flex-direction: column;
        gap: 15px;
    }
    
    .button-group {
        width: 100%;
        justify-content: center;
    }
}

/* AI分数和长度显示 */
.ai-score, .ai-length {
    color: #ff3366;
    text-shadow: 0 0 5px rgba(255, 51, 102, 0.5);
    font-weight: bold;
    margin-top: 5px;
}

/* AI规则样式 */
.ai-rules {
    margin-top: 20px;
    padding: 15px;
    background: rgba(255, 51, 102, 0.1);
    border-radius: 8px;
    border: 1px solid rgba(255, 51, 102, 0.3);
}

.ai-rules h3 {
    color: #ff3366;
    margin-bottom: 10px;
}

.ai-rules ul {
    list-style-type: none;
    padding-left: 0;
}

.ai-rules li {
    margin: 5px 0;
    color: #ff3366;
    font-size: 0.9em;
}

/* 游戏规则容器 */
.game-rules {
    margin-top: 20px;
    padding: 20px;
    background: rgba(0, 247, 255, 0.1);
    border-radius: 10px;
    border: 1px solid rgba(0, 247, 255, 0.3);
}

.game-rules h3 {
    color: #00f7ff;
    margin-bottom: 10px;
}

.game-rules ul {
    list-style-type: none;
    padding-left: 0;
}

.game-rules li {
    margin: 5px 0;
    color: #00f7ff;
    font-size: 0.9em;
}

/* 控制按钮样式 */
.control-group {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 10px 0;
}

button {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    background: #00f7ff;
    color: #000;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;
}

button:hover {
    background: #00ff88;
    transform: translateY(-2px);
}

button.secondary-btn {
    background: #ff3366;
    color: #fff;
}

button.secondary-btn:hover {
    background: #ff0066;
}

/* 速度控制样式 */
#speedControl {
    width: 150px;
    height: 5px;
    -webkit-appearance: none;
    background: #00f7ff;
    border-radius: 5px;
    outline: none;
}

#speedControl::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 15px;
    height: 15px;
    background: #00ff88;
    border-radius: 50%;
    cursor: pointer;
}

/* 难度选择样式 */
#difficultySelect {
    padding: 8px;
    border: 1px solid #00f7ff;
    border-radius: 4px;
    background: transparent;
    color: #00f7ff;
    cursor: pointer;
    font-size: 14px;
    outline: none;
}

#difficultySelect option {
    background: #000;
    color: #00f7ff;
}

/* 响应式布局 */
@media (max-width: 800px) {
    .game-container {
        padding: 10px;
    }
    
    .game-header {
        flex-direction: column;
    }
    
    .score-container {
        margin-bottom: 10px;
    }
    
    .control-group {
        flex-wrap: wrap;
    }
    
    button {
        flex: 1;
        min-width: 100px;
    }
}

/* 结算界面样式 */
.game-over-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.85);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    opacity: 0;
    transition: opacity 0.5s;
    pointer-events: none;
}

.game-over-modal.active {
    opacity: 1;
    pointer-events: auto;
}

.modal-content {
    background: linear-gradient(135deg, #0a0a2e 0%, #0d182e 100%);
    border: 2px solid #00f7ff;
    box-shadow: 0 0 30px rgba(0, 247, 255, 0.5);
    border-radius: 10px;
    padding: 30px;
    width: 90%;
    max-width: 500px;
    text-align: center;
    position: relative;
    transform: translateY(-50px);
    transition: transform 0.5s;
    overflow: hidden;
}

.game-over-modal.active .modal-content {
    transform: translateY(0);
}

.modal-content::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 4px;
    background: linear-gradient(90deg, #00ff88, #00f7ff);
    animation: rainbow 3s linear infinite;
}

@keyframes rainbow {
    0% { background-position: 0% 50%; }
    50% { background-position: 100% 50%; }
    100% { background-position: 0% 50%; }
}

.modal-title {
    color: #fff;
    font-size: 32px;
    margin: 0 0 20px;
    font-weight: 700;
    text-shadow: 0 0 10px rgba(0, 247, 255, 0.7);
}

.normal-mode .modal-title {
    color: #00f7ff;
}

.obstacle-mode .modal-title {
    color: #d4b483;
}

.ai-mode .modal-title {
    color: #ff3366;
}

.score-container {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.score-item {
    display: flex;
    justify-content: space-between;
    padding: 8px 10px;
    border-radius: 5px;
    background: rgba(0, 0, 0, 0.2);
}

.score-label {
    color: rgba(255, 255, 255, 0.7);
}

.score-value {
    font-weight: bold;
    color: #fff;
}

.player-stats {
    border-left: 3px solid #00ff88;
    background: rgba(0, 255, 136, 0.1);
}

.ai-stats {
    border-left: 3px solid #ff3366;
    background: rgba(255, 51, 102, 0.1);
}

.high-score {
    border-left: 3px solid #ffff00;
    background: rgba(255, 255, 0, 0.1);
}

.game-time {
    border-left: 3px solid #00f7ff;
    background: rgba(0, 247, 255, 0.1);
}

.mode-badge {
    display: inline-block;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 15px;
    text-transform: uppercase;
}

.normal-mode .mode-badge {
    background: rgba(0, 247, 255, 0.2);
    color: #00f7ff;
    border: 1px solid #00f7ff;
}

.obstacle-mode .mode-badge {
    background: rgba(212, 180, 131, 0.2);
    color: #d4b483;
    border: 1px solid #d4b483;
}

.ai-mode .mode-badge {
    background: rgba(255, 51, 102, 0.2);
    color: #ff3366;
    border: 1px solid #ff3366;
}

.buttons-container {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin-top: 20px;
}

.modal-button {
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 16px;
    min-width: 120px;
}

.restart-btn {
    background: linear-gradient(135deg, #00ff88 0%, #00f7ff 100%);
    color: #000;
}

.restart-btn:hover {
    background: linear-gradient(135deg, #00f7ff 0%, #00ff88 100%);
    box-shadow: 0 0 15px rgba(0, 247, 255, 0.5);
}

.menu-btn {
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.menu-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

.share-btn {
    background: linear-gradient(135deg, #ff3366 0%, #ff9933 100%);
    color: #fff;
}

.share-btn:hover {
    background: linear-gradient(135deg, #ff9933 0%, #ff3366 100%);
    box-shadow: 0 0 15px rgba(255, 51, 102, 0.5);
}

.score-animation {
    animation: scoreGlow 1s ease-in-out;
}

@keyframes scoreGlow {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); color: #00ff88; text-shadow: 0 0 10px #00ff88; }
    100% { transform: scale(1); }
}

/* 粒子背景 */
.particles-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: -1;
}

.modal-particle {
    position: absolute;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    opacity: 0;
    animation: floatParticle 5s infinite linear;
}

@keyframes floatParticle {
    0% { transform: translateY(100px); opacity: 0; }
    10% { opacity: 1; }
    90% { opacity: 0.8; }
    100% { transform: translateY(-100px); opacity: 0; }
} 
</style>
</head>
<body>
  <div class="game-wrapper">
    <div class="game-header">
        <h1>贪吃蛇游戏</h1>
        <div class="game-info">
            <div class="score-board">
                <span id="score">分数: 0</span>
                <span id="highScore">最高分: 0</span>
            </div>
            <div class="game-stats">
                <span id="length">长度: 1</span>
                <span id="time">时间: 0s</span>
            </div>
            <div id="aiScore" class="ai-score">AI分数: 0</div>
            <div id="aiLength" class="ai-length">AI长度: 1</div>
        </div>
        <div id="effects" class="effects-container"></div>
    </div>

    <div class="game-container">
        <canvas id="gameCanvas" width="800" height="600"></canvas>
        
        <div class="game-controls">
            <div class="control-group">
                <label for="speedControl">速度:</label>
                <input type="range" id="speedControl" min="1" max="10" value="5">
                <span id="speedValue">5</span>
            </div>
            
            <div class="control-group">
                <label for="difficultySelect">难度:</label>
                <select id="difficultySelect" class="difficulty-select">
                    <option value="easy">简单</option>
                    <option value="medium" selected>中等</option>
                    <option value="hard">困难</option>
                </select>
            </div>
            
            <div class="button-group">
                <button id="startBtn" class="primary-btn">开始游戏</button>
                <button id="pauseBtn" class="secondary-btn">暂停</button>
                <button id="restartBtn" class="secondary-btn">重新开始</button>
                <button id="obstacleModeBtn" class="secondary-btn">障碍模式</button>
                <button id="aiModeBtn" class="secondary-btn">AI对战</button>
            </div>
        </div>
    </div>

    <div class="game-footer">
        <div class="game-instructions">
            <h2>游戏说明</h2>
            <div class="instructions-content">
                <div class="control-instructions">
                    <h3>控制方式</h3>
                    <ul>
                        <li>↑ 向上移动</li>
                        <li>↓ 向下移动</li>
                        <li>← 向左移动</li>
                        <li>→ 向右移动</li>
                        <li>空格键 暂停/继续</li>
                    </ul>
                </div>
                <div class="game-rules">
                    <h3>游戏规则</h3>
                    <ul>
                        <li>吃到食物可以增加长度和分数</li>
                        <li>撞到墙壁或自身会导致游戏结束</li>
                        <li>速度越快，得分越高</li>
                        <li>障碍模式：游戏区域会出现随机障碍物，增加游戏难度</li>
                        <li>护盾效果可以穿过墙壁、自身和障碍物</li>
                    </ul>
                </div>
                <div class="food-types">
                    <h3>特殊食物</h3>
                    <ul>
                        <li><span class="food-icon normal"></span> 普通食物: 10分</li>
                        <li><span class="food-icon speedBoost"></span> 加速食物: 15分, 速度提升</li>
                        <li><span class="food-icon doubleScore"></span> 双倍分数: 20分, 得分翻倍</li>
                        <li><span class="food-icon shield"></span> 护盾食物: 25分, 免疫碰撞</li>
                    </ul>
                </div>
                <div class="ai-rules">
                    <h3>AI对战模式</h3>
                    <ul>
                        <li>开启AI对战模式后，将出现一条AI控制的蛇</li>
                        <li>AI蛇会自动寻找最短路径吃到食物</li>
                        <li>与AI蛇相撞会导致游戏结束</li>
                        <li>可以同时开启障碍模式增加难度</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加结算界面 -->
<div class="game-over-modal" id="gameOverModal">
    <div class="modal-content">
        <div class="particles-container" id="modalParticles"></div>
        <span class="mode-badge" id="modeBadge">标准模式</span>
        <h2 class="modal-title">游戏结束</h2>
        <div class="score-container">
            <div class="score-item player-stats">
                <span class="score-label">玩家分数</span>
                <span class="score-value" id="finalScore">0</span>
            </div>
            <div class="score-item player-stats">
                <span class="score-label">玩家长度</span>
                <span class="score-value" id="finalLength">0</span>
            </div>
            <div class="score-item ai-stats" id="aiStatsContainer" style="display: none;">
                <span class="score-label">AI分数</span>
                <span class="score-value" id="finalAiScore">0</span>
            </div>
            <div class="score-item ai-stats" id="aiLengthContainer" style="display: none;">
                <span class="score-label">AI长度</span>
                <span class="score-value" id="finalAiLength">0</span>
            </div>
            <div class="score-item high-score">
                <span class="score-label">最高分数</span>
                <span class="score-value" id="finalHighScore">0</span>
            </div>
            <div class="score-item game-time">
                <span class="score-label">游戏时间</span>
                <span class="score-value" id="finalTime">0秒</span>
            </div>
        </div>
        <div class="buttons-container">
            <button class="modal-button restart-btn" id="modalRestartBtn">重新开始</button>
            <button class="modal-button menu-btn" id="modalMenuBtn">返回菜单</button>
            <button class="modal-button share-btn" id="modalShareBtn">分享成绩</button>
        </div>
    </div>
</div>

    <script>
      // 游戏状态管理
const game = {
    snake: [{x: 15, y: 15}],  // 蛇的初始位置
    aiSnake: [{x: 25, y: 15}], // AI蛇的初始位置
    food: {x: 5, y: 5, type: 'normal'},  // 食物的初始位置和类型
    direction: 'right',       // 初始方向
    aiDirection: 'left', // AI蛇的方向
    gridSize: 20,            // 网格大小
    speed: 200,              // 初始速度（毫秒）
    score: 0,                // 当前分数
    aiScore: 0, // AI的分数
    highScore: 0,            // 最高分
    isRunning: false,        // 游戏运行状态
    isPaused: false,         // 游戏暂停状态
    startTime: 0,            // 游戏开始时间
    gameTime: 0,             // 游戏运行时间
    obstacleMode: false,     // 障碍模式状态
    obstacles: [],           // 障碍物数组
    difficulty: 'medium',    // 游戏难度
    aiMode: false, // AI对战模式
    effects: {               // 特殊效果状态
        speedBoost: false,   // 速度提升
        speedBoostEndTime: 0,// 速度提升结束时间
        doubleScore: false,  // 双倍分数
        doubleScoreEndTime: 0,// 双倍分数结束时间
        shield: false,       // 护盾
        shieldEndTime: 0     // 护盾结束时间
    }
};

// 难度设置
const DIFFICULTY_SETTINGS = {
    easy: {
        obstacleCount: {min: 3, max: 5},
        foodProbability: {normal: 0.8, speedBoost: 0.07, doubleScore: 0.07, shield: 0.06},
        scoreMultiplier: 1
    },
    medium: {
        obstacleCount: {min: 5, max: 8},
        foodProbability: {normal: 0.7, speedBoost: 0.1, doubleScore: 0.1, shield: 0.1},
        scoreMultiplier: 1.5
    },
    hard: {
        obstacleCount: {min: 8, max: 12},
        foodProbability: {normal: 0.6, speedBoost: 0.15, doubleScore: 0.15, shield: 0.1},
        scoreMultiplier: 2
    }
};

// AI难度设置
const AI_DIFFICULTY_SETTINGS = {
    easy: {
        pathUpdateInterval: 1000, // 路径更新间隔（毫秒）
        pathfindingAccuracy: 0.8, // 路径规划准确度
        reactionDelay: 500 // 反应延迟（毫秒）
    },
    medium: {
        pathUpdateInterval: 800,
        pathfindingAccuracy: 0.9,
        reactionDelay: 300
    },
    hard: {
        pathUpdateInterval: 500,
        pathfindingAccuracy: 1.0,
        reactionDelay: 100
    }
};

// 食物类型定义
const FOOD_TYPES = {
    normal: {
        color: '#ff0066',
        score: 10,
        probability: 0.7,
        effect: null
    },
    speedBoost: {
        color: '#00ff88',
        score: 15,
        probability: 0.1,
        effect: 'speedBoost',
        duration: 5000 // 5秒
    },
    doubleScore: {
        color: '#ffff00',
        score: 20,
        probability: 0.1,
        effect: 'doubleScore',
        duration: 8000 // 8秒
    },
    shield: {
        color: '#00f7ff',
        score: 25,
        probability: 0.1,
        effect: 'shield',
        duration: 10000 // 10秒
    }
};

// 获取画布上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 初始化游戏
function initGame() {
    // 重置游戏状态
    game.snake = [{x: 15, y: 15}];
    game.aiSnake = [{x: 25, y: 15}];
    game.direction = 'right';
    game.aiDirection = 'left';
    game.score = 0;
    game.aiScore = 0;
    game.isRunning = false;
    game.isPaused = false;
    game.startTime = 0;
    game.gameTime = 0;
    game.obstacles = [];
    
    // 重置特殊效果
    game.effects = {
        speedBoost: false,
        speedBoostEndTime: 0,
        doubleScore: false,
        doubleScoreEndTime: 0,
        shield: false,
        shieldEndTime: 0
    };
    
    // 生成第一个食物
    generateFood();
    
    // 如果障碍模式开启，生成障碍物
    if (game.obstacleMode) {
        generateObstacles();
    }
    
    // 更新显示
    updateDisplay();
    
    // 绘制初始状态
    draw();
}

// 更新显示
function updateDisplay() {
    // 更新分数
    document.getElementById('score').textContent = `分数: ${game.score}`;
    document.getElementById('highScore').textContent = `最高分: ${game.highScore}`;
    
    // 更新长度
    document.getElementById('length').textContent = `长度: ${game.snake.length}`;
    
    // 更新时间
    document.getElementById('time').textContent = `时间: ${Math.floor(game.gameTime)}s`;
    
    // 更新AI分数显示
    if (game.aiMode) {
        document.getElementById('aiScore').textContent = `AI分数: ${game.aiScore}`;
        document.getElementById('aiLength').textContent = `AI长度: ${game.aiSnake.length}`;
    }
    
    // 更新速度显示
    document.getElementById('speedValue').textContent = 
        Math.floor((11 - (game.speed - 75) / 25)).toString();
    
    // 更新特殊效果显示
    updateEffectsDisplay();
}

// 更新特殊效果显示
function updateEffectsDisplay() {
    const effectsContainer = document.getElementById('effects');
    if (!effectsContainer) return;
    
    effectsContainer.innerHTML = '';
    
    if (game.effects.speedBoost) {
        const timeLeft = Math.ceil((game.effects.speedBoostEndTime - Date.now()) / 1000);
        if (timeLeft > 0) {
            addEffectElement('加速', timeLeft, '#00ff88');
        } else {
            game.effects.speedBoost = false;
        }
    }
    
    if (game.effects.doubleScore) {
        const timeLeft = Math.ceil((game.effects.doubleScoreEndTime - Date.now()) / 1000);
        if (timeLeft > 0) {
            addEffectElement('双倍分数', timeLeft, '#ffff00');
        } else {
            game.effects.doubleScore = false;
        }
    }
    
    if (game.effects.shield) {
        const timeLeft = Math.ceil((game.effects.shieldEndTime - Date.now()) / 1000);
        if (timeLeft > 0) {
            addEffectElement('护盾', timeLeft, '#00f7ff');
        } else {
            game.effects.shield = false;
        }
    }
}

// 添加效果元素
function addEffectElement(name, timeLeft, color) {
    const effectsContainer = document.getElementById('effects');
    const effectElement = document.createElement('div');
    effectElement.className = 'effect-item';
    effectElement.style.color = color;
    effectElement.textContent = `${name}: ${timeLeft}s`;
    effectsContainer.appendChild(effectElement);
}

// 生成食物
function generateFood() {
    const gridWidth = canvas.width / game.gridSize;
    const gridHeight = canvas.height / game.gridSize;
    
    let validPosition = false;
    let x, y;
    
    // 尝试找到一个有效的位置（不在蛇身上，不在障碍物上）
    while (!validPosition) {
        x = Math.floor(Math.random() * gridWidth);
        y = Math.floor(Math.random() * gridHeight);
        
        // 检查是否与蛇重叠
        const onSnake = game.snake.some(segment => segment.x === x && segment.y === y);
        
        // 检查是否与障碍物重叠
        const onObstacle = game.obstacleMode && game.obstacles.some(obs => obs.x === x && obs.y === y);
        
        if (!onSnake && !onObstacle) {
            validPosition = true;
        }
    }
    
    // 设置食物位置
    game.food.x = x;
    game.food.y = y;
    
    // 随机选择食物类型
    game.food.type = selectFoodType();
}

// 选择食物类型
function selectFoodType() {
    const difficultySetting = DIFFICULTY_SETTINGS[game.difficulty];
    const probabilities = difficultySetting.foodProbability;
    
    const random = Math.random();
    let cumulativeProbability = 0;
    
    // 按照概率选择食物类型
    for (const [type, probability] of Object.entries(probabilities)) {
        cumulativeProbability += probability;
        if (random <= cumulativeProbability) {
            return type;
        }
    }
    
    // 默认返回普通食物
    return 'normal';
}

// 应用食物效果
function applyFoodEffect(foodType) {
    const food = FOOD_TYPES[foodType];
    if (!food.effect) return;
    
    switch (food.effect) {
        case 'speedBoost':
            game.effects.speedBoost = true;
            game.effects.speedBoostEndTime = Date.now() + food.duration;
            // 速度提升50%
            game.speed = Math.max(50, game.speed * 0.5);
            break;
        case 'doubleScore':
            game.effects.doubleScore = true;
            game.effects.doubleScoreEndTime = Date.now() + food.duration;
            break;
        case 'shield':
            game.effects.shield = true;
            game.effects.shieldEndTime = Date.now() + food.duration;
            break;
    }
    
    // 创建粒子特效
    createParticles(game.food.x * game.gridSize + game.gridSize/2, 
                   game.food.y * game.gridSize + game.gridSize/2, 
                   food.color);
}

// 检查位置是否在蛇身上
function isPositionOnSnake(x, y) {
    return game.snake.some(segment => segment.x === x && segment.y === y);
}

// 绘制游戏画面
function draw() {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制网格背景
    drawGrid();
    
    // 绘制障碍物
    if (game.obstacleMode) {
        drawObstacles();
    }
    
    // 绘制玩家蛇
    drawSnake(game.snake, true);
    
    // 绘制AI蛇
    if (game.aiMode) {
        drawSnake(game.aiSnake, false);
    }
    
    // 绘制食物
    drawFood();
    
    // 绘制粒子
    drawParticles();
}

// 绘制蛇
function drawSnake(snake, isPlayer) {
    snake.forEach((segment, index) => {
        const gradient = ctx.createLinearGradient(
            segment.x * game.gridSize,
            segment.y * game.gridSize,
            (segment.x + 1) * game.gridSize,
            (segment.y + 1) * game.gridSize
        );
        
        if (index === 0) {
            // 蛇头
            if (isPlayer) {
                gradient.addColorStop(0, '#00ff88');
                gradient.addColorStop(1, '#00f7ff');
            } else {
                gradient.addColorStop(0, '#ff3366');
                gradient.addColorStop(1, '#ff0066');
            }
        } else {
            // 蛇身
            const hue = isPlayer ? 180 - (index * 2) : 340 - (index * 2);
            gradient.addColorStop(0, `hsl(${hue}, 100%, 50%)`);
            gradient.addColorStop(1, `hsl(${hue + 20}, 100%, 50%)`);
        }
        
        ctx.fillStyle = gradient;
        ctx.fillRect(
            segment.x * game.gridSize,
            segment.y * game.gridSize,
            game.gridSize - 2,
            game.gridSize - 2
        );
        
        // 添加光晕效果
        ctx.shadowColor = isPlayer ? '#00f7ff' : '#ff0066';
        ctx.shadowBlur = 10;
        ctx.fillRect(
            segment.x * game.gridSize,
            segment.y * game.gridSize,
            game.gridSize - 2,
            game.gridSize - 2
        );
        ctx.shadowBlur = 0;
    });
}

// 绘制食物
function drawFood() {
    const foodType = FOOD_TYPES[game.food.type];
    const foodGradient = ctx.createRadialGradient(
        game.food.x * game.gridSize + game.gridSize/2,
        game.food.y * game.gridSize + game.gridSize/2,
        0,
        game.food.x * game.gridSize + game.gridSize/2,
        game.food.y * game.gridSize + game.gridSize/2,
        game.gridSize/2
    );
    
    // 根据食物类型设置颜色
    foodGradient.addColorStop(0, foodType.color);
    foodGradient.addColorStop(1, adjustColor(foodType.color, -30));
    
    ctx.fillStyle = foodGradient;
    ctx.beginPath();
    ctx.arc(
        game.food.x * game.gridSize + game.gridSize/2,
        game.food.y * game.gridSize + game.gridSize/2,
        game.gridSize/2 - 2,
        0,
        Math.PI * 2
    );
    ctx.fill();
    
    // 添加食物光晕
    ctx.shadowColor = foodType.color;
    ctx.shadowBlur = 15;
    ctx.fill();
    ctx.shadowBlur = 0;
    
    // 绘制特殊食物的图标
    if (game.food.type !== 'normal') {
        drawFoodIcon(game.food.x, game.food.y, game.food.type);
    }
}

// 调整颜色亮度
function adjustColor(color, amount) {
    const hex = color.replace('#', '');
    const r = Math.max(0, Math.min(255, parseInt(hex.substr(0, 2), 16) + amount));
    const g = Math.max(0, Math.min(255, parseInt(hex.substr(2, 2), 16) + amount));
    const b = Math.max(0, Math.min(255, parseInt(hex.substr(4, 2), 16) + amount));
    return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
}

// 绘制食物图标
function drawFoodIcon(x, y, type) {
    const centerX = x * game.gridSize + game.gridSize/2;
    const centerY = y * game.gridSize + game.gridSize/2;
    const size = game.gridSize/3;
    
    ctx.fillStyle = '#fff';
    ctx.strokeStyle = '#000';
    ctx.lineWidth = 1;
    
    switch (type) {
        case 'speedBoost':
            // 绘制闪电图标
            ctx.beginPath();
            ctx.moveTo(centerX, centerY - size);
            ctx.lineTo(centerX - size/2, centerY);
            ctx.lineTo(centerX + size/2, centerY);
            ctx.lineTo(centerX, centerY + size);
            ctx.closePath();
            ctx.fill();
            ctx.stroke();
            break;
        case 'doubleScore':
            // 绘制星星图标
            drawStar(centerX, centerY, 5, size, size/2);
            break;
        case 'shield':
            // 绘制盾牌图标
            ctx.beginPath();
            ctx.arc(centerX, centerY, size, 0, Math.PI * 2);
            ctx.fill();
            ctx.stroke();
            break;
    }
}

// 绘制星星
function drawStar(cx, cy, spikes, outerRadius, innerRadius) {
    let rot = Math.PI / 2 * 3;
    let x = cx;
    let y = cy;
    let step = Math.PI / spikes;

    ctx.beginPath();
    ctx.moveTo(cx, cy - outerRadius);
    
    for (let i = 0; i < spikes; i++) {
        x = cx + Math.cos(rot) * outerRadius;
        y = cy + Math.sin(rot) * outerRadius;
        ctx.lineTo(x, y);
        rot += step;

        x = cx + Math.cos(rot) * innerRadius;
        y = cy + Math.sin(rot) * innerRadius;
        ctx.lineTo(x, y);
        rot += step;
    }
    
    ctx.lineTo(cx, cy - outerRadius);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
}

// 粒子系统
let particles = [];

// 创建粒子
function createParticles(x, y, color) {
    for (let i = 0; i < 30; i++) {
        particles.push({
            x: x,
            y: y,
            vx: (Math.random() - 0.5) * 8,
            vy: (Math.random() - 0.5) * 8,
            size: Math.random() * 4 + 2,
            color: color,
            alpha: 1,
            life: Math.random() * 30 + 20
        });
    }
}

// 绘制粒子
function drawParticles() {
    for (let i = particles.length - 1; i >= 0; i--) {
        const p = particles[i];
        
        ctx.fillStyle = `rgba(${hexToRgb(p.color)}, ${p.alpha})`;
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
        ctx.fill();
        
        // 更新粒子
        p.x += p.vx;
        p.y += p.vy;
        p.alpha -= 0.02;
        p.life--;
        
        // 移除消失的粒子
        if (p.alpha <= 0 || p.life <= 0) {
            particles.splice(i, 1);
        }
    }
}

// 十六进制颜色转RGB
function hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? 
        `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}` : 
        '255, 255, 255';
}

// 绘制网格背景
function drawGrid() {
    ctx.strokeStyle = 'rgba(0, 247, 255, 0.1)';
    ctx.lineWidth = 0.5;
    
    for (let i = 0; i <= canvas.width; i += game.gridSize) {
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, canvas.height);
        ctx.stroke();
    }
    
    for (let i = 0; i <= canvas.height; i += game.gridSize) {
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(canvas.width, i);
        ctx.stroke();
    }
}

// 绘制障碍物
function drawObstacles() {
    if (!game.obstacleMode || !game.obstacles.length) return;
    
    game.obstacles.forEach(obstacle => {
        // 创建障碍物渐变
        const gradient = ctx.createLinearGradient(
            obstacle.x * game.gridSize,
            obstacle.y * game.gridSize,
            (obstacle.x + 1) * game.gridSize,
            (obstacle.y + 1) * game.gridSize
        );
        
        gradient.addColorStop(0, '#d4b483');
        gradient.addColorStop(1, '#8b6b43');
        
        ctx.fillStyle = gradient;
        
        // 绘制障碍物主体
        ctx.fillRect(
            obstacle.x * game.gridSize,
            obstacle.y * game.gridSize,
            game.gridSize,
            game.gridSize
        );
        
        // 添加纹理效果
        ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
        ctx.fillRect(
            obstacle.x * game.gridSize + 2,
            obstacle.y * game.gridSize + 2,
            game.gridSize - 4,
            game.gridSize - 4
        );
        
        // 添加边框和发光效果
        ctx.strokeStyle = '#a89060';
        ctx.lineWidth = 2;
        ctx.shadowColor = 'rgba(212, 180, 131, 0.5)';
        ctx.shadowBlur = 10;
        ctx.strokeRect(
            obstacle.x * game.gridSize,
            obstacle.y * game.gridSize,
            game.gridSize,
            game.gridSize
        );
        ctx.shadowBlur = 0;
    });
}

// 事件监听器
document.getElementById('startBtn').addEventListener('click', () => {
    if (!game.isRunning) {
        game.isRunning = true;
        game.startTime = Date.now();
        gameLoop();
    }
});

document.getElementById('pauseBtn').addEventListener('click', () => {
    if (game.isRunning) {
        game.isPaused = !game.isPaused;
        if (!game.isPaused) {
            gameLoop();
        }
    }
});

document.getElementById('restartBtn').addEventListener('click', () => {
    initGame();
});

document.getElementById('obstacleModeBtn').addEventListener('click', () => {
    toggleObstacleMode();
});

document.getElementById('aiModeBtn').addEventListener('click', () => {
    toggleAIMode();
});

document.getElementById('difficultySelect').addEventListener('change', (e) => {
    game.difficulty = e.target.value;
    console.log(`难度已更改为: ${game.difficulty}`);
    
    // 如果游戏正在运行，重新生成障碍物
    if (game.isRunning && game.obstacleMode) {
        generateObstacles();
    }
});

document.getElementById('speedControl').addEventListener('input', (e) => {
    const baseSpeed = 300 - e.target.value * 25;  // 1-10级映射到75-275ms
    game.speed = game.effects.speedBoost ? baseSpeed * 0.5 : baseSpeed;
    document.getElementById('speedValue').textContent = e.target.value;
});

// 键盘控制
document.addEventListener('keydown', (e) => {
    if (e.key === ' ' && game.isRunning) {
        game.isPaused = !game.isPaused;
        if (!game.isPaused) {
            gameLoop();
        }
        return;
    }
    
    if (!game.isRunning || game.isPaused) return;
    
    // 阻止方向键的默认行为（页面滚动）
    if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
        e.preventDefault();
    }
    
    switch(e.key) {
        case 'ArrowUp':
            if (game.direction !== 'down') game.direction = 'up';
            break;
        case 'ArrowDown':
            if (game.direction !== 'up') game.direction = 'down';
            break;
        case 'ArrowLeft':
            if (game.direction !== 'right') game.direction = 'left';
            break;
        case 'ArrowRight':
            if (game.direction !== 'left') game.direction = 'right';
            break;
    }
});

// 移动蛇
function moveSnake() {
    const head = {...game.snake[0]};
    
    // 根据方向移动蛇头
    switch(game.direction) {
        case 'up': head.y--; break;
        case 'down': head.y++; break;
        case 'left': head.x--; break;
        case 'right': head.x++; break;
    }
    
    // 检查是否吃到食物
    if (head.x === game.food.x && head.y === game.food.y) {
        // 计算得分
        const score = calculateScore(game.food.type);
        
        game.score += score;
        if (game.score > game.highScore) {
            game.highScore = game.score;
        }
        
        // 应用食物效果
        applyFoodEffect(game.food.type);
        
        // 生成新食物
        generateFood();
    } else {
        game.snake.pop(); // 如果没吃到食物，移除尾部
    }
    
    // 检查碰撞
    if (checkCollision(head)) {
        gameOver();
        return;
    }
    
    // 添加新的头部
    game.snake.unshift(head);
}

// 碰撞检测
function checkCollision(head) {
    // 检查墙壁碰撞
    if (head.x < 0 || head.x >= canvas.width / game.gridSize ||
        head.y < 0 || head.y >= canvas.height / game.gridSize) {
        return !game.effects.shield; // 如果有护盾，可以穿过墙壁
    }
    
    // 检查自身碰撞
    const selfCollision = game.snake.some(segment => segment.x === head.x && segment.y === head.y);
    if (selfCollision && !game.effects.shield) {
        return true; // 如果有护盾，可以穿过自身
    }
    
    // 检查障碍物碰撞
    if (game.obstacleMode) {
        const obstacleCollision = game.obstacles.some(obs => obs.x === head.x && obs.y === head.y);
        if (obstacleCollision && !game.effects.shield) {
            return true; // 如果有护盾，可以穿过障碍物
        }
    }
    
    return false;
}

// 游戏结束处理
function gameOver() {
    game.isRunning = false;
    
    // 更新结算界面内容
    document.getElementById('finalScore').textContent = game.score;
    document.getElementById('finalLength').textContent = game.snake.length;
    document.getElementById('finalHighScore').textContent = game.highScore;
    document.getElementById('finalTime').textContent = `${Math.floor(game.gameTime)}秒`;
    
    // 根据游戏模式设置界面样式
    const modal = document.getElementById('gameOverModal');
    const modalContent = modal.querySelector('.modal-content');
    
    // 重置所有模式样式
    modalContent.classList.remove('normal-mode', 'obstacle-mode', 'ai-mode');
    
    // 设置模式标签
    const modeBadge = document.getElementById('modeBadge');
    
    if (game.aiMode) {
        modalContent.classList.add('ai-mode');
        modeBadge.textContent = 'AI对战模式';
        modeBadge.style.display = 'inline-block';
        
        // 显示AI数据
        document.getElementById('aiStatsContainer').style.display = 'flex';
        document.getElementById('aiLengthContainer').style.display = 'flex';
        document.getElementById('finalAiScore').textContent = game.aiScore;
        document.getElementById('finalAiLength').textContent = game.aiSnake.length;
        
        // 确定胜负
        const result = game.score > game.aiScore ? '你赢了！' : (game.score < game.aiScore ? 'AI赢了！' : '平局！');
        document.querySelector('.modal-title').textContent = result;
    } else if (game.obstacleMode) {
        modalContent.classList.add('obstacle-mode');
        modeBadge.textContent = '障碍模式';
        modeBadge.style.display = 'inline-block';
        
        // 隐藏AI数据
        document.getElementById('aiStatsContainer').style.display = 'none';
        document.getElementById('aiLengthContainer').style.display = 'none';
        
        document.querySelector('.modal-title').textContent = '游戏结束';
    } else {
        modalContent.classList.add('normal-mode');
        modeBadge.textContent = '标准模式';
        modeBadge.style.display = 'inline-block';
        
        // 隐藏AI数据
        document.getElementById('aiStatsContainer').style.display = 'none';
        document.getElementById('aiLengthContainer').style.display = 'none';
        
        document.querySelector('.modal-title').textContent = '游戏结束';
    }
    
    // 应用分数动画
    document.getElementById('finalScore').classList.add('score-animation');
    setTimeout(() => {
        document.getElementById('finalScore').classList.remove('score-animation');
    }, 1000);
    
    // 创建粒子背景
    createModalParticles();
    
    // 显示结算界面
    modal.classList.add('active');
    
    // 添加按钮事件监听
    document.getElementById('modalRestartBtn').addEventListener('click', () => {
        modal.classList.remove('active');
        initGame();
        game.isRunning = true;
        game.startTime = Date.now();
        gameLoop();
    });
    
    document.getElementById('modalMenuBtn').addEventListener('click', () => {
        modal.classList.remove('active');
        initGame();
    });
    
    document.getElementById('modalShareBtn').addEventListener('click', () => {
        shareScore();
    });
}

// 创建结算界面粒子
function createModalParticles() {
    const container = document.getElementById('modalParticles');
    container.innerHTML = '';
    
    // 根据不同模式创建不同颜色的粒子
    let colors = ['#00ff88', '#00f7ff'];
    
    if (game.obstacleMode) {
        colors = ['#d4b483', '#8b6b43', '#a89060'];
    }
    
    if (game.aiMode) {
        colors = ['#ff3366', '#ff0066', '#ff9933'];
    }
    
    // 创建30个粒子
    for (let i = 0; i < 30; i++) {
        const particle = document.createElement('div');
        particle.className = 'modal-particle';
        
        // 随机位置
        const posX = Math.random() * 100;
        const posY = Math.random() * 100 + 50;
        
        // 随机大小
        const size = Math.random() * 6 + 3;
        
        // 随机颜色
        const color = colors[Math.floor(Math.random() * colors.length)];
        
        // 随机动画延迟
        const delay = Math.random() * 5;
        
        // 随机动画时长
        const duration = Math.random() * 5 + 5;
        
        // 应用样式
        particle.style.left = `${posX}%`;
        particle.style.bottom = `-${posY}px`;
        particle.style.width = `${size}px`;
        particle.style.height = `${size}px`;
        particle.style.backgroundColor = color;
        particle.style.animationDelay = `${delay}s`;
        particle.style.animationDuration = `${duration}s`;
        
        container.appendChild(particle);
    }
}

// 分享分数
function shareScore() {
    let shareText = `我在贪吃蛇游戏中获得了 ${game.score} 分，长度达到了 ${game.snake.length}！`;
    
    if (game.obstacleMode) {
        shareText += '（障碍模式）';
    }
    
    if (game.aiMode) {
        const result = game.score > game.aiScore ? '战胜了AI！' : (game.score < game.aiScore ? '被AI击败了。' : '与AI打成了平手！');
        shareText += `在AI对战中${result}`;
    }
    
    // 如果支持Navigator Share API
    if (navigator.share) {
        navigator.share({
            title: '贪吃蛇游戏成绩',
            text: shareText
        }).catch(console.error);
    } else {
        // 复制到剪贴板
        navigator.clipboard.writeText(shareText).then(() => {
            alert('分享文本已复制到剪贴板！');
        }).catch(err => {
            console.error('复制失败: ', err);
            alert('分享失败，请手动复制：\n' + shareText);
        });
    }
}

// 游戏主循环
function gameLoop() {
    if (!game.isRunning || game.isPaused) return;
    
    // 检查特殊效果是否过期
    checkEffects();
    
    // 移动玩家蛇
    moveSnake();
    
    // 移动AI蛇
    if (game.aiMode) {
        moveAISnake();
    }
    
    game.gameTime = (Date.now() - game.startTime) / 1000;
    updateDisplay();
    draw();
    
    setTimeout(gameLoop, game.speed);
}

// 检查特殊效果是否过期
function checkEffects() {
    const now = Date.now();
    
    // 检查速度提升效果
    if (game.effects.speedBoost && now >= game.effects.speedBoostEndTime) {
        game.effects.speedBoost = false;
        // 恢复原始速度
        const speedValue = document.getElementById('speedControl').value;
        game.speed = 300 - speedValue * 25;
    }
    
    // 检查双倍分数效果
    if (game.effects.doubleScore && now >= game.effects.doubleScoreEndTime) {
        game.effects.doubleScore = false;
    }
    
    // 检查护盾效果
    if (game.effects.shield && now >= game.effects.shieldEndTime) {
        game.effects.shield = false;
    }
}

// 生成障碍物
function generateObstacles() {
    const gridWidth = canvas.width / game.gridSize;
    const gridHeight = canvas.height / game.gridSize;
    
    // 清空现有障碍物
    game.obstacles = [];
    
    // 根据难度设置生成障碍物
    const difficultySetting = DIFFICULTY_SETTINGS[game.difficulty];
    const minObstacles = difficultySetting.obstacleCount.min;
    const maxObstacles = difficultySetting.obstacleCount.max;
    const obstacleCount = Math.floor(Math.random() * (maxObstacles - minObstacles + 1)) + minObstacles;
    
    console.log(`准备生成 ${obstacleCount} 个障碍物`); // 添加调试日志
    
    for (let i = 0; i < obstacleCount; i++) {
        let x, y;
        let validPosition = false;
        let attempts = 0;
        
        // 尝试找到一个有效的位置（不在蛇身上，不在食物上，不在其他障碍物上）
        while (!validPosition && attempts < 100) {
            x = Math.floor(Math.random() * gridWidth);
            y = Math.floor(Math.random() * gridHeight);
            
            // 检查是否与蛇重叠
            const onSnake = game.snake.some(segment => segment.x === x && segment.y === y);
            
            // 检查是否与食物重叠
            const onFood = game.food.x === x && game.food.y === y;
            
            // 检查是否与其他障碍物重叠
            const onObstacle = game.obstacles.some(obs => obs.x === x && obs.y === y);
            
            // 检查是否在蛇头周围（避免一开始就堵住蛇）
            const nearHead = Math.abs(x - game.snake[0].x) <= 2 && Math.abs(y - game.snake[0].y) <= 2;
            
            if (!onSnake && !onFood && !onObstacle && !nearHead) {
                validPosition = true;
            }
            attempts++;
        }
        
        if (validPosition) {
            game.obstacles.push({x, y});
            console.log(`生成障碍物: x=${x}, y=${y}`); // 添加调试日志
        }
    }
    
    console.log(`最终生成 ${game.obstacles.length} 个障碍物`); // 添加调试日志
}

// 切换障碍模式
function toggleObstacleMode() {
    game.obstacleMode = !game.obstacleMode;
    
    // 更新按钮文本
    const obstacleModeBtn = document.getElementById('obstacleModeBtn');
    obstacleModeBtn.textContent = game.obstacleMode ? '关闭障碍' : '障碍模式';
    
    // 立即生成或清除障碍物
    if (game.obstacleMode) {
        generateObstacles();
        console.log('障碍物已生成:', game.obstacles);
    } else {
        game.obstacles = [];
    }
    
    // 重新绘制游戏画面
    draw();
}

// 计算得分
function calculateScore(foodType) {
    const baseScore = FOOD_TYPES[foodType].score;
    const difficultySetting = DIFFICULTY_SETTINGS[game.difficulty];
    const scoreMultiplier = difficultySetting.scoreMultiplier;
    
    // 根据难度设置计算得分
    let score = Math.floor(baseScore * scoreMultiplier);
    
    // 如果有双倍分数效果，得分翻倍
    if (game.effects.doubleScore) {
        score *= 2;
    }
    
    return score;
}

// 移动AI蛇
function moveAISnake() {
    if (!game.aiMode) return;
    
    const head = {...game.aiSnake[0]};
    const path = findPathToFood(head, game.food);
    
    if (path && path.length > 1) {
        const nextStep = path[1];
        const dx = nextStep.x - head.x;
        const dy = nextStep.y - head.y;
        
        // 根据路径更新AI蛇的方向
        if (dx > 0) game.aiDirection = 'right';
        else if (dx < 0) game.aiDirection = 'left';
        else if (dy > 0) game.aiDirection = 'down';
        else if (dy < 0) game.aiDirection = 'up';
    }
    
    // 根据方向移动AI蛇头
    switch(game.aiDirection) {
        case 'up': head.y--; break;
        case 'down': head.y++; break;
        case 'left': head.x--; break;
        case 'right': head.x++; break;
    }
    
    // 检查是否吃到食物
    if (head.x === game.food.x && head.y === game.food.y) {
        game.aiScore += calculateScore(game.food.type);
        generateFood();
    } else {
        game.aiSnake.pop();
    }
    
    // 检查碰撞
    if (checkAICollision(head)) {
        gameOver();
        return;
    }
    
    game.aiSnake.unshift(head);
}

// 检查AI蛇的碰撞
function checkAICollision(head) {
    // 检查墙壁碰撞
    if (head.x < 0 || head.x >= canvas.width / game.gridSize ||
        head.y < 0 || head.y >= canvas.height / game.gridSize) {
        return true;
    }
    
    // 检查自身碰撞
    const selfCollision = game.aiSnake.some(segment => segment.x === head.x && segment.y === head.y);
    if (selfCollision) {
        return true;
    }
    
    // 检查与玩家蛇的碰撞
    const playerCollision = game.snake.some(segment => segment.x === head.x && segment.y === head.y);
    if (playerCollision) {
        return true;
    }
    
    // 检查障碍物碰撞
    if (game.obstacleMode) {
        const obstacleCollision = game.obstacles.some(obs => obs.x === head.x && obs.y === head.y);
        if (obstacleCollision) {
            return true;
        }
    }
    
    return false;
}

// A*寻路算法
function findPathToFood(start, target) {
    const gridWidth = canvas.width / game.gridSize;
    const gridHeight = canvas.height / game.gridSize;
    
    // 创建开放列表和关闭列表
    const openList = [];
    const closedList = new Set();
    
    // 创建起点节点
    const startNode = {
        x: start.x,
        y: start.y,
        g: 0,
        h: Math.abs(target.x - start.x) + Math.abs(target.y - start.y),
        parent: null
    };
    startNode.f = startNode.g + startNode.h;
    
    openList.push(startNode);
    
    while (openList.length > 0) {
        // 获取F值最小的节点
        openList.sort((a, b) => a.f - b.f);
        const current = openList.shift();
        
        // 到达目标
        if (current.x === target.x && current.y === target.y) {
            const path = [];
            let node = current;
            while (node) {
                path.unshift({x: node.x, y: node.y});
                node = node.parent;
            }
            return path;
        }
        
        // 将当前节点加入关闭列表
        closedList.add(`${current.x},${current.y}`);
        
        // 检查相邻节点
        const neighbors = [
            {x: current.x + 1, y: current.y},
            {x: current.x - 1, y: current.y},
            {x: current.x, y: current.y + 1},
            {x: current.x, y: current.y - 1}
        ];
        
        for (const neighbor of neighbors) {
            // 检查边界
            if (neighbor.x < 0 || neighbor.x >= gridWidth ||
                neighbor.y < 0 || neighbor.y >= gridHeight) {
                continue;
            }
            
            // 检查是否在关闭列表中
            if (closedList.has(`${neighbor.x},${neighbor.y}`)) {
                continue;
            }
            
            // 检查是否与蛇身重叠
            const onSnake = game.snake.some(segment => 
                segment.x === neighbor.x && segment.y === neighbor.y);
            const onAISnake = game.aiSnake.some(segment => 
                segment.x === neighbor.x && segment.y === neighbor.y);
            
            if (onSnake || onAISnake) {
                continue;
            }
            
            // 检查是否与障碍物重叠
            if (game.obstacleMode) {
                const onObstacle = game.obstacles.some(obs => 
                    obs.x === neighbor.x && obs.y === neighbor.y);
                if (onObstacle) {
                    continue;
                }
            }
            
            // 计算G值
            const g = current.g + 1;
            
            // 检查是否在开放列表中
            const existingNode = openList.find(node => 
                node.x === neighbor.x && node.y === neighbor.y);
            
            if (existingNode) {
                if (g < existingNode.g) {
                    existingNode.g = g;
                    existingNode.f = g + existingNode.h;
                    existingNode.parent = current;
                }
            } else {
                const h = Math.abs(target.x - neighbor.x) + Math.abs(target.y - neighbor.y);
                openList.push({
                    x: neighbor.x,
                    y: neighbor.y,
                    g: g,
                    h: h,
                    f: g + h,
                    parent: current
                });
            }
        }
    }
    
    return null; // 没有找到路径
}

// 切换AI模式
function toggleAIMode() {
    game.aiMode = !game.aiMode;
    
    // 更新按钮文本
    const aiModeBtn = document.getElementById('aiModeBtn');
    aiModeBtn.textContent = game.aiMode ? '关闭AI' : 'AI对战';
    
    // 重置AI蛇
    if (game.aiMode) {
        game.aiSnake = [{x: 25, y: 15}];
        game.aiDirection = 'left';
        game.aiScore = 0;
        
        // 如果游戏没有运行，启动游戏
        if (!game.isRunning) {
            game.isRunning = true;
            game.startTime = Date.now();
            gameLoop();
        }
    }
    
    // 重新绘制游戏画面
    draw();
}

// 初始化游戏
initGame(); 
    </script>
</body>
</html> 